// i8042.cc

#include <stdio.h>
#include <string.h>
#include <i386/console.h>
#include <i386/io.h>
#include <i386/mem.h>
#include <errno.h>

#include "i8042.h"

#include <kernel.h>
#include <mutex.h>
#include <syscall.h>
#include <Thread.h>
#include <Process.h>
#include <platform/Timer.h>
#include <platform/Interrupt.h>

#if 0
#define dbg printf
#else
#define dbg(fmt, ...)
#endif

#define likely(a) a

static void interruptTask(void *);
static bool interruptHandler(regs_t *regs);

static int_mutex_t i8042_lock = INT_MUTEX_UNLOCKED;

struct i8042_values {
	int irqHandle;
	int irq;
	unsigned char disable;
	unsigned char irqen;
	unsigned char exists;
	signed char mux;
	char name[8];
	spinlock_t cond;
	tid_t tid;
	void (*handler)(int irq, unsigned char data, unsigned long dfl);
};

static struct i8042_values i8042_kbd_values = {
	0,
	0,
	I8042_CTR_KBDDIS,
	I8042_CTR_KBDINT,
	0,
	-1,
	"KBD",
	SPINLOCK_LOCKED,
	0,
	0,
};

static struct i8042_values i8042_aux_values = {
	0,
	0,
	I8042_CTR_AUXDIS,
	I8042_CTR_AUXINT,
	0,
	-1,
	"AUX",
	SPINLOCK_LOCKED,
	0,
	0,
};

int i8042_bind(int port, void (*handler)(int irq, unsigned char data,
	unsigned long dfl)) {
	i8042_values * values = 0;
	
	switch (port) {
		case I8042_BIND_KBD:
			values = &i8042_kbd_values;
			break;
		case I8042_BIND_AUX:
			values = &i8042_aux_values;
			break;
	}
	
	if (values && handler) {
		values->handler = handler;
		
		RefThread thread = Thread::createThread(interruptTask, values,
			values->name, Process::getSystemProcess());
		values->tid = thread->getTid();
		thread->run();
		
		return 0;
	} else {
		return -ENODEV;
	}
}

static unsigned int i8042_noaux;
static unsigned int i8042_nomux = 1;
static unsigned int i8042_unlock;
static unsigned int i8042_reset;
static unsigned int i8042_direct;
static unsigned int i8042_dumbkbd;
static unsigned int i8042_noloop;
static int i8042_noacpi;

static unsigned char i8042_initial_ctr;
static unsigned char i8042_ctr;
static unsigned char i8042_mux_open;
static unsigned char i8042_mux_present;
//static sys_timer_t i8042_timer;

static int i8042_open(i8042_values *values);
static int i8042_interrupt(int irq);

/*
#define rdtsc(low,high) \
     __asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high))
          
static uint64 cpuTicksPerMicro;
static inline uint64 getMicroTime(void) {
	timestamp_t now;
	rdtsc(now.low, now.high);
	
	return now.value / cpuTicksPerMicro;
}
*/

static inline void udelay(uint32 delay) {
	uint64 start = Timer::getMicroTime();
	
	while (start + delay > Timer::getMicroTime());
}

static void interruptTask(void *param) {
	i8042_values *values = (i8042_values *) param;
	
	dbg("interruptTask: handling irq %02x\n", values->irq);
	
	if (i8042_open(values) != 0) {
		dbg("interruptTask: open irq %02x failed\n", values->irq);
		
		return;
	}
	
	dbg("interruptTask: opened irq %02x\n", values->irq);
	
	do {
		while (spinlock_try(&values->cond) != 0) {
			syscall(SYSCALL_THREAD, SYSCALL_THREAD_WAIT);
		}
		
		i8042_interrupt(values->irq);
	} while (true);
}		

static bool interruptHandler(regs_t *regs) {
	if (regs->which_int == i8042_kbd_values.irq) {
		spinlock_signal(&i8042_kbd_values.cond);
		syscall(SYSCALL_THREAD, SYSCALL_THREAD_NOTIFY, i8042_kbd_values.tid);
		
		return true;
	} else if (regs->which_int == i8042_aux_values.irq) {
		spinlock_signal(&i8042_aux_values.cond);
		syscall(SYSCALL_THREAD, SYSCALL_THREAD_NOTIFY, i8042_aux_values.tid);
		
		return true;
	}
	
	return false;
}

static void disbatch_interrupt(i8042_values *values, unsigned char data,
	unsigned long dfl) {
	dbg("disbatch_interrupt: irq %02x, data %02x, flags %08x\n", values->irq,
		data, dfl);
	
	if (values->handler) {
		values->handler(values->irq, data, dfl);
	} 
}

/*
 * The i8042_wait_read() and i8042_wait_write functions wait for the i8042 to
 * be ready for reading values from it / writing values to it.
 * Called always with i8042_lock held.
 */

static int i8042_wait_read(void)
{
	//dbg("i8042_wait_read\n");
	int i = 0;
	while ((~i8042_read_status() & I8042_STR_OBF) && (i < I8042_CTL_TIMEOUT)) {
		udelay(50);
		i++;
	}
	return -(i == I8042_CTL_TIMEOUT);
}

static int i8042_wait_write(void)
{
	//dbg("i8042_wait_write\n");
	int i = 0;
	while ((i8042_read_status() & I8042_STR_IBF) && (i < I8042_CTL_TIMEOUT)) {
		udelay(50);
		i++;
	}
	return -(i == I8042_CTL_TIMEOUT);
}

/*
 * i8042_flush() flushes all data that may be in the keyboard and mouse buffers
 * of the i8042 down the toilet.
 */

static int i8042_flush(void)
{
	unsigned char data;
	int i = 0;

	interrupt_mutex_wait(&i8042_lock);

	while ((i8042_read_status() & I8042_STR_OBF) && (i++ < I8042_BUFFER_SIZE)) {
		udelay(50);
		data = i8042_read_data();
		dbg("%02x <- i8042 (flush, %s)", data,
			i8042_read_status() & I8042_STR_AUXDATA ? "aux" : "kbd");
	}

	interrupt_mutex_signal(&i8042_lock);

	return i;
}

/*
 * i8042_command() executes a command on the i8042. It also sends the input
 * parameter(s) of the commands to it, and receives the output value(s). The
 * parameters are to be stored in the param array, and the output is placed
 * into the same array. The number of the parameters and output values is
 * encoded in bits 8-11 of the command number.
 */

static int i8042_command(unsigned char *param, int command)
{
	int retval = 0, i = 0;

	if (i8042_noloop && command == I8042_CMD_AUX_LOOP)
		return -1;

	interrupt_mutex_wait(&i8042_lock);

	retval = i8042_wait_write();
	if (!retval) {
		dbg("%02x -> i8042 (command)\n", command & 0xff);
		i8042_write_command(command & 0xff);
	}

	if (!retval)
		for (i = 0; i < ((command >> 12) & 0xf); i++) {
			if ((retval = i8042_wait_write())) break;
			dbg("%02x -> i8042 (parameter)\n", param[i]);
			i8042_write_data(param[i]);
		}

	if (!retval)
		for (i = 0; i < ((command >> 8) & 0xf); i++) {
			if ((retval = i8042_wait_read())) break;
			if (i8042_read_status() & I8042_STR_AUXDATA)
				param[i] = ~i8042_read_data();
			else
				param[i] = i8042_read_data();
			dbg("%02x <- i8042 (return)\n", param[i]);
		}

	interrupt_mutex_signal(&i8042_lock);

	if (retval)
		dbg("     -- i8042 (timeout)\n");

	return retval;
}

/*
 * i8042_kbd_write() sends a byte out through the keyboard interface.
 */

int i8042_kbd_write(/*i8042_values *values, */unsigned char c)
{
	int retval = 0;

	interrupt_mutex_wait(&i8042_lock);

	if(!(retval = i8042_wait_write())) {
		dbg("%02x -> i8042 (kbd-data)", c);
		i8042_write_data(c);
	}

	interrupt_mutex_signal(&i8042_lock);

	return retval;
}

/*
 * i8042_aux_write() sends a byte out through the aux interface.
 */

int i8042_aux_write(/*i8042_values *values, */unsigned char c)
{
	int retval;

/*
 * Send the byte out.
 */

	//if (values->mux == -1)
		retval = i8042_command(&c, I8042_CMD_AUX_SEND);
	//else
	//	retval = i8042_command(&c, I8042_CMD_MUX_SEND + values->mux);

/*
 * Make sure the interrupt happens and the character is received even
 * in the case the IRQ isn't wired, so that we can receive further
 * characters later.
 */

	i8042_interrupt(0);
	return retval;
}

/*
 * i8042_activate_port() enables port on a chip.
 */

static int i8042_activate_port(i8042_values *values)
{
	i8042_flush();

	/*
	 * Enable port again here because it is disabled if we are
	 * resuming (normally it is enabled already).
	 */
	i8042_ctr &= ~values->disable;

	i8042_ctr |= values->irqen;

	if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) {
		i8042_ctr &= ~values->irqen;
		return -1;
	}

	return 0;
}

static int i8042_open(i8042_values *values)
{
	if (values->mux != -1) {
		if (i8042_mux_open++) {
			return 0;
		}
	}
	
	Interrupt::registerHandler(values->irq, interruptHandler);

	if (i8042_activate_port(values)) {
		dbg("i8042.c: Can't activate %s, unregistering the port\n", values->name);
		goto activate_fail;
	}

	i8042_interrupt(0);

	return 0;

activate_fail:
	Interrupt::unregisterHandler(values->irq, interruptHandler);
	values->exists = 0;

	return -1;
}

/*
 * i8042_interrupt() is the most important function in this driver -
 * it handles the interrupts from the i8042, and sends incoming bytes
 * to the upper layers.
 */

static int i8042_interrupt(int irq)
{
	unsigned char str, data = 0;
	unsigned int dfl;
	unsigned int aux_idx;
	int ret;

	//timer_setTimer(i8042_timer, 0, 1000000000*I8042_POLL_PERIOD, false);

	interrupt_mutex_wait(&i8042_lock);
	str = i8042_read_status();
	if (str & I8042_STR_OBF)
		data = i8042_read_data();
	interrupt_mutex_signal(&i8042_lock);

	if (~str & I8042_STR_OBF) {
		if (irq) dbg("Interrupt %02x, without any data\n", irq);
		ret = 0;
		goto out;
	}
#if 0
	if (i8042_mux_present && (str & I8042_STR_AUXDATA)) {
		static unsigned long last_transmit;
		static unsigned char last_str;

		dfl = 0;
		if (str & I8042_STR_MUXERR) {
			dbg("MUX error, status is %02x, data is %02x", str, data);
			switch (data) {
				default:
/*
 * When MUXERR condition is signalled the data register can only contain
 * 0xfd, 0xfe or 0xff if implementation follows the spec. Unfortunately
 * it is not always the case. Some KBC just get confused which port the
 * data came from and signal error leaving the data intact. They _do not_
 * revert to legacy mode (actually I've never seen KBC reverting to legacy
 * mode yet, when we see one we'll add proper handling).
 * Anyway, we will assume that the data came from the same serio last byte
 * was transmitted (if transmission happened not too long ago).
 */
					if (time_before(jiffies, last_transmit + HZ/10)) {
						str = last_str;
						break;
					}
					/* fall through - report timeout */
				case 0xfd:
				case 0xfe: dfl = SERIO_TIMEOUT; data = 0xfe; break;
				case 0xff: dfl = SERIO_PARITY;  data = 0xfe; break;
			}
		}

		aux_idx = (str >> 6) & 3;

		dbg("%02x <- i8042 (interrupt, aux%d, %02x%s%s)\n",
			data, aux_idx, irq,
			dfl & SERIO_PARITY ? ", bad parity" : "",
			dfl & SERIO_TIMEOUT ? ", timeout" : "");

		if (likely(i8042_mux_values[aux_idx].exists))
			serio_interrupt(i8042_mux_port[aux_idx], data, dfl, regs);

		last_str = str;
		last_transmit = jiffies;
		goto irq_ret;
	}
#endif

	dfl = ((str & I8042_STR_PARITY) ? I8042_STR_PARITY : 0) |
	      ((str & I8042_STR_TIMEOUT) ? I8042_STR_TIMEOUT : 0);

	dbg("%02x <- i8042 (interrupt, %s, %02x%s%s)\n",
		data, (str & I8042_STR_AUXDATA) ? "aux" : "kbd", irq,
		dfl & I8042_STR_PARITY ? ", bad parity" : "",
		dfl & I8042_STR_TIMEOUT ? ", timeout" : "");


	if (str & I8042_STR_AUXDATA) {
		if (likely(i8042_aux_values.exists))
			disbatch_interrupt(&i8042_aux_values, data, dfl);
	} else {
		if (likely(i8042_kbd_values.exists))
			disbatch_interrupt(&i8042_kbd_values, data, dfl);
	}

irq_ret:
	ret = 1;
out:
	return ret;
}

/*
 * i8042_set_mux_mode checks whether the controller has an active
 * multiplexor and puts the chip into Multiplexed (1) or Legacy (0) mode.
 */

static int i8042_set_mux_mode(unsigned int mode, unsigned char *mux_version)
{

	unsigned char param;
/*
 * Get rid of bytes in the queue.
 */

	i8042_flush();

/*
 * Internal loopback test - send three bytes, they should come back from the
 * mouse interface, the last should be version. Note that we negate mouseport
 * command responses for the i8042_check_aux() routine.
 */

	param = 0xf0;
	if (i8042_command(&param, I8042_CMD_AUX_LOOP) || param != 0x0f)
		return -1;
	param = mode ? 0x56 : 0xf6;
	if (i8042_command(&param, I8042_CMD_AUX_LOOP) || param != (mode ? 0xa9 : 0x09))
		return -1;
	param = mode ? 0xa4 : 0xa5;
	if (i8042_command(&param, I8042_CMD_AUX_LOOP) || param == (mode ? 0x5b : 0x5a))
		return -1;

	if (mux_version)
		*mux_version = ~param;

	return 0;
}


/*
 * i8042_enable_mux_ports enables 4 individual AUX ports after
 * the controller has been switched into Multiplexed mode
 */

static int i8042_enable_mux_ports(struct i8042_values *values)
{
	unsigned char param;
	int i;
/*
 * Disable all muxed ports by disabling AUX.
 */

	i8042_ctr |= I8042_CTR_AUXDIS;
	i8042_ctr &= ~I8042_CTR_AUXINT;

	if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) {
		dbg("i8042.c: Failed to disable AUX port, can't use MUX.\n");
		return -1;
	}

/*
 * Enable all muxed ports.
 */

	for (i = 0; i < 4; i++) {
		i8042_command(&param, I8042_CMD_MUX_PFX + i);
		i8042_command(&param, I8042_CMD_AUX_ENABLE);
	}

	return 0;
}


/*
 * i8042_check_mux() checks whether the controller supports the PS/2 Active
 * Multiplexing specification by Synaptics, Phoenix, Insyde and
 * LCS/Telegraphics.
 */

static int i8042_check_mux(struct i8042_values *values)
{
	unsigned char mux_version;

	if (i8042_set_mux_mode(1, &mux_version))
		return -1;

	/* Workaround for interference with USB Legacy emulation */
	/* that causes a v10.12 MUX to be found. */
	if (mux_version == 0xAC)
		return -1;

	dbg("i8042.c: Detected active multiplexing controller, rev %d.%d.\n",
		(mux_version >> 4) & 0xf, mux_version & 0xf);

	if (i8042_enable_mux_ports(values))
		return -1;

	i8042_mux_present = 1;
	return 0;
}


/*
 * i8042_check_aux() applies as much paranoia as it can at detecting
 * the presence of an AUX interface.
 */

static int i8042_check_aux(struct i8042_values *values)
{
	unsigned char param;
	static int i8042_check_aux_cookie;

/*
 * Check if AUX irq is available. If it isn't, then there is no point
 * in trying to detect AUX presence.
 */

	// ...

/*
 * Get rid of bytes in the queue.
 */

	i8042_flush();

/*
 * Internal loopback test - filters out AT-type i8042's. Unfortunately
 * SiS screwed up and their 5597 doesn't support the LOOP command even
 * though it has an AUX port.
 */

	param = 0x5a;
	if (i8042_command(&param, I8042_CMD_AUX_LOOP) || param != 0xa5) {

/*
 * External connection test - filters out AT-soldered PS/2 i8042's
 * 0x00 - no error, 0x01-0x03 - clock/data stuck, 0xff - general error
 * 0xfa - no error on some notebooks which ignore the spec
 * Because it's common for chipsets to return error on perfectly functioning
 * AUX ports, we test for this only when the LOOP command failed.
 */

		if (i8042_command(&param, I8042_CMD_AUX_TEST)
		    	|| (param && param != 0xfa && param != 0xff))
				return -1;
	}

/*
 * Bit assignment test - filters out PS/2 i8042's in AT mode
 */

	if (i8042_command(&param, I8042_CMD_AUX_DISABLE))
		return -1;
	if (i8042_command(&param, I8042_CMD_CTL_RCTR) || (~param & I8042_CTR_AUXDIS)) {
		dbg("Failed to disable AUX port, but continuing anyway... Is this a SiS?\n");
		dbg("If AUX port is really absent please use the 'i8042.noaux' option.\n");
	}

	if (i8042_command(&param, I8042_CMD_AUX_ENABLE))
		return -1;
	if (i8042_command(&param, I8042_CMD_CTL_RCTR) || (param & I8042_CTR_AUXDIS))
		return -1;

/*
 * Disable the interface.
 */

	i8042_ctr |= I8042_CTR_AUXDIS;
	i8042_ctr &= ~I8042_CTR_AUXINT;

	if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR))
		return -1;

	return 0;
}


/*
 * i8042_port_register() marks the device as existing,
 * registers it, and reports to the user.
 */

static int i8042_port_register(i8042_values *values)
{
	values->exists = 1;

	i8042_ctr &= ~values->disable;

	if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) {
		dbg("i8042.c: Can't write CTR while registering.\n");
		values->exists = 0;
		return -1;
	}

	dbg("serio: i8042 %s port at %02x,%02x irq %02x\n",
	       values->name,
	       I8042_DATA_REG,
	       I8042_COMMAND_REG,
	       values->irq);

	//serio_register_port(port);

	return 0;
}

/*
static void i8042_timer_func(sys_timer_t timer)
{
	i8042_interrupt(0);
}
*/

/*
 * i8042_controller init initializes the i8042 controller, and,
 * most importantly, sets it into non-xlated mode if that's
 * desired.
 */

static int i8042_controller_init(void)
{
/*
 * Test the i8042. We need to know if it thinks it's working correctly
 * before doing anything else.
 */

	i8042_flush();

	if (i8042_reset) {

		unsigned char param;

		if (i8042_command(&param, I8042_CMD_CTL_TEST)) {
			dbg("i8042.c: i8042 controller self test timeout.\n");
			return -1;
		}

		if (param != I8042_RET_CTL_TEST) {
			dbg("i8042.c: i8042 controller selftest failed. (%#x != %#x)\n",
				 param, I8042_RET_CTL_TEST);
			return -1;
		}
	}

/*
 * Save the CTR for restoral on unload / reboot.
 */

	if (i8042_command(&i8042_ctr, I8042_CMD_CTL_RCTR)) {
		dbg("i8042.c: Can't read CTR while initializing i8042.\n");
		return -1;
	}

	i8042_initial_ctr = i8042_ctr;

/*
 * Disable the keyboard interface and interrupt.
 */

	i8042_ctr |= I8042_CTR_KBDDIS;
	i8042_ctr &= ~I8042_CTR_KBDINT;

/*
 * Handle keylock.
 */

	interrupt_mutex_wait(&i8042_lock);
	if (~i8042_read_status() & I8042_STR_KEYLOCK) {
		if (i8042_unlock)
			i8042_ctr |= I8042_CTR_IGNKEYLOCK;
		 else
			dbg("i8042.c: Warning: Keylock active.\n");
	}
	interrupt_mutex_signal(&i8042_lock);

/*
 * If the chip is configured into nontranslated mode by the BIOS, don't
 * bother enabling translating and be happy.
 */

	if (~i8042_ctr & I8042_CTR_XLATE)
		i8042_direct = 1;

/*
 * Set nontranslated mode for the kbd interface if requested by an option.
 * After this the kbd interface becomes a simple serial in/out, like the aux
 * interface is. We don't do this by default, since it can confuse notebook
 * BIOSes.
 */

	if (i8042_direct)
		i8042_ctr &= ~I8042_CTR_XLATE;

/*
 * Write CTR back.
 */

	if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) {
		dbg("i8042.c: Can't write CTR while initializing i8042.\n");
		return -1;
	}

	return 0;
}


/*
 * Reset the controller.
 */
void i8042_controller_reset(void)
{
	unsigned char param;

/*
 * Reset the controller if requested.
 */

	if (i8042_reset)
		if (i8042_command(&param, I8042_CMD_CTL_TEST))
			dbg("i8042.c: i8042 controller reset timeout.\n");

/*
 * Disable MUX mode if present.
 */

	if (i8042_mux_present)
		i8042_set_mux_mode(0, NULL);

/*
 * Restore the original control register setting.
 */

	i8042_ctr = i8042_initial_ctr;

	if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR))
		dbg("i8042.c: Can't restore CTR.\n");
}

int i8042_init(void)
{
	int i;
	int err;

	//i8042_timer = timer_createTimer(i8042_timer_func);

	i8042_aux_values.irq = INT_PS2MOUSE;
	i8042_kbd_values.irq = INT_KEYBOARD;

	if (i8042_controller_init())
		return -ENODEV;

	// register driver

	if (!i8042_noaux && !i8042_check_aux(&i8042_aux_values)) {
		i8042_port_register(&i8042_aux_values);
	}

	i8042_port_register(&i8042_kbd_values);

	//timer_setTimer(i8042_timer, 0, 1000000000 * I8042_POLL_PERIOD, false);
	syscall(SYSCALL_THREAD, SYSCALL_THREAD_SLEEP, I8042_POLL_PERIOD*1000);
	i8042_interrupt(0);

	return 0;
}
